const app = getApp()
const api = require('../../utils/utils')
Page({
  data: {
    iconUrl: api.iconUrl,
    loginForm: {
      account: '', // 手机号
      password: '', // 密码
      sms_code: '', // 验证码
    },
    send_status: true, // 控制发送验证码按钮
    remain_time: 60, // 获取验证码间隔时间
    phone_number: '', // 提前获取的手机号
    login_mode: 0, // 登录模式： 0 密码登录 1 手机验证码登录
    rules: {
      account: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        },
        {
          pattern: '/^[1]([3-9])[0-9]{9}$/',
          message: '手机号不合法',
          trigger: 'blur'
        }
      ],
      password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          min: 8,
          max: 20,
          message: '密码长度在8-20个字符之间',
          trigger: 'blur'
        },
        {
          pattern: '^[A-Za-z0-9]+$',
          message: '密码必须由数字字母组成',
          trigger: 'blur'
        }
      ],
      sms_code: [{
          required: true,
          message: '请输入验证码',
        },
        {
          min: 6,
          max: 6,
          message: '验证码为6个数字组成',
          trigger: 'blur'
        },
        {
          pattern: '^[0-9]+$',
          message: '验证码必须由数字组成',
          trigger: 'blur'
        }
      ],
    },
  },
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '登录'
    })
  },
  onShow:function(){
    wx.lin.initValidateForm(this) // 表单初始化
  },
  // 提交表单登录
  submit(event) {
    const form = event.detail.values
    let data = {}
    let url = ''
    // 输入合法后发送登录请求
    if (event.detail.isValidate !== false) {
      if (this.data.login_mode == 0) {
        // 手机号密码表单
        url = '/authorizations/psw/'
        data = {
          "account": form.account,
          "password": form.password
        }
      } else {
        // 手机验证码表单
        url = '/authorizations/phone/'
        data = {
          "username": form.account,
          "sms_code": form.sms_code,
        }
      }
      this.login(url, data)
    }
  },
  // 发送登录请求
  login(url, data) {
    const toast = this.selectComponent("#mytoast")
    api.request('post', url, data, false)
      .then(res => {
        if (res.usertype != 'D') {
          toast.linShow({
            title: "登录失败",
            icon: 'error'
          })
          return
        }
        toast.linShow({
          title: "登录成功",
          icon: 'success'
        })
        wx.setStorageSync('token', res.token);
        app.globalData.isLogin = true
        setTimeout(() => {
          wx.navigateBack({
            delta: 1,
          })
        }, 800)
      })
      .catch(err => {
        toast.linShow({
          title: "登录失败",
          icon: 'error'
        })
      })
  },
  // 跳转到注册页面
  enroll() {
    wx.navigateTo({
      url: '/pages/enroll/enroll',
    })
  },
  // 登录模式切换
  phone_login() {
    this.setData({
      login_mode: 1
    })
  },
  pwd_login() {
    this.setData({
      login_mode: 0
    })
  },
  // 提前获取手机号
  set_phone_number(event) {
    const {
      detail
    } = event
    this.setData({
      phone_number: detail.value
    })
  },
  // 获取短信验证码
  send_code() {
    const toast = this.selectComponent("#mytoast")
    // 判断手机号是否已经注册
    api.request('get', `/usernames/${this.data.phone_number}/count/`, {}, false)
      .then(res => {
        // 手机号已经注册则发送短信
        if (res.count === 1) {
          api.request('get', `/sms_codes/${this.data.phone_number}/`, {}, false)
            .then(res => {
              this.setData({
                send_status: false
              })
              toast.linShow({
                title: "验证码发送成功",
                icon: "success"
              })
              // 验证码倒计时
              let time = setInterval(() => {
                let remain_time = this.data.remain_time;
                remain_time--;
                this.setData({
                  remain_time: remain_time
                });
                if (remain_time == 0) {
                  clearInterval(time);
                  this.setData({
                    remain_time: 60,
                    send_status: true
                  });
                }
              }, 1000)
            })
            .catch(err => {
              console.log(err.data)
              toast.linShow({
                title: "验证码发送失败，请检查手机号是否正确",
                icon: "error"
              })
            })
        } else {
          toast.linShow({
            title: "该账号未注册",
            icon: 'error'
          })
        }
      })
  },
})